<template>
  <NuxtLayout name="sign">
    <div class="sign-wrapper">
      <h2 class="site-name">WATT权限管理系统</h2>
      <div class="title-tab">
        <span @click.stop="goLink">密码登录</span>
        <span class="active">验证码登录</span>
      </div>

      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        class="login-form"
        layout="vertical"
        @keydown.enter="handleSubmit">
        <div>
          <a-form-item label="手机号" name="phone">
            <a-input v-model:value="form.phone" size="large" allowClear placeholder="手机号">
              <template #prefix>
                <phone-outlined class="pre-icon" />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item label="验证码" name="code">
            <a-input v-model:value="form.code" allowClear size="large" placeholder="验证码">
              <template #prefix>
                <safety-outlined class="pre-icon" />
              </template>
              <template #suffix>
                <a-button type="primary" size="small" ghost @click.stop="validatePhone">{{codeTxt}}</a-button>
              </template>
            </a-input>
          </a-form-item>
        </div>

        <a-form-item class="login-form-btn">
          <a-button type="primary" block :loading="loading" @click="handleSubmit"> 验证码登录 </a-button>
          <div class="tip"><span>手机验证码登录，无需注册</span></div>
        </a-form-item>
      </a-form>

      <validate v-model:visible="phoned" :scene="form.scene" @on-ok="handleSendSms"></validate>
    </div>
  </NuxtLayout>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { Cookie } from '@wattjs/network'
import Validate from '../components/common/validate.vue'

import { baseURL as publicPath } from '../api/config'
import { sendSmsCode, loginBySmsCode } from '../api/user.model'

let DTIME
const route = useRoute()
const loading = ref(false)
const formRef = ref()

const coding = ref(false) // 倒计时中
const codeTxt = ref('获取验证码')
const phoned = ref(false) // 获取验证码成功

const form = reactive({
  phone: '',
  code: '',
  scene: 'login'
})
const rules = ref({
  phone: [{
    required: true,
    min: 11,
    max: 11,
    pattern: '^1[3-9][0-9]{9}$',
    message: '手机号格式不正确'
  }],
  code: [{
    required: true,
    min: 6,
    max: 6,
    pattern: '[0-9a-zA-Z]{4}',
    message: '请正确输入验证码'
  }]
})

const timer = (num) => {
  DTIME && clearTimeout(DTIME)
  if (num >= 0) {
    coding.value = true
    codeTxt.value = `${num}s`
    DTIME = setTimeout(() => {
      timer(--num)
    }, 1000)
  } else {
    coding.value = false
    codeTxt.value = '获取验证码'
  }
}

const validatePhone = () => {
  if (coding.value) return
  formRef.value.validateFields(['phone']).then(() => {
    phoned.value = true
  })
}

const handleSendSms = (captcha) => {
  if (!captcha) {
    message.error('请输入图形验证码')
    return
  }
  sendSmsCode.send({
    phone: form.phone,
    captcha,
    scene: form.scene
  }).then(res => {
    if (res && res.phone) {
      timer(60)
    }
  }).catch(err => {

  })
}

const handleSubmit = () => {
  if (loading.value) return
  formRef.value
    .validate()
    .then(() => {
      loading.value = true
      loginBySmsCode.send({
        phone: form.phone,
        code: form.code,
        scene: form.scene,
      }).then(async (res) => {
        loading.value = false
        const { uid, nickname, token, tokenExpired } = res
        const baseURL = process.client ? window.location.hostname : ''
        Cookie.set('op_id', uid, { expires: new Date(tokenExpired), domain: baseURL })
        Cookie.set('op_name', nickname, { expires: new Date(tokenExpired), domain: baseURL })
        Cookie.set('token', token, { expires: new Date(tokenExpired), domain: baseURL })
        await navigateTo(`${publicPath}`, { external: true })
      }).catch(() => {
        loading.value = false
      })
    })
}

const goLink = async () => {
  await navigateTo(`${publicPath.replace(/\/$/, '')}/login`, { external: true })
}
</script>
<style lang="less" scoped>
@import "../assets/less/sign.less";

</style>
